<!-- pd.vue -->
<template>
  <div class="pd-container">
    <!-- 频谱图 -->
    <div class="chart-wrapper">
      <h3>频谱图</h3>
      <div ref="spectrumRef" class="chart"></div>
    </div>

    <!-- 瀑布图 -->
    <div class="chart-wrapper">
      <h3>频谱瀑布图</h3>
      <div ref="waterfallRef" class="chart"></div>
    </div>

    <!-- 噪声/信标扫描（你原来的柱状图） -->
    <div class="signal-chart-container">
      <h3>噪声/信标扫描</h3>
      <div ref="beaconRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from "vue"
import * as echarts from "echarts"

// ========== Props：接收历史频谱数据 ==========
const props = defineProps({
  frequencies: { type: Array, default: () => [] },
  freqLabels: { type: Array, default: () => [] },
  dbValues: { type: Array, default: () => [] },
  waterfallData: { type: Array, default: () => [] },
  waterfallTimes: { type: Array, default: () => [] }
})

// ========== refs ==========
const spectrumRef = ref(null)
const waterfallRef = ref(null)
const beaconRef = ref(null)

let spectrumChart = null
let waterfallChart = null
let beaconChart = null

// ========== 工具函数 ==========
function getAxisLabel(target) {
  if (!props.frequencies.length) {
    return target.toFixed(2)
  }
  const closest = props.frequencies.reduce((a, b) =>
    Math.abs(b - target) < Math.abs(a - target) ? b : a
  )
  return closest.toFixed(2)
}

function generateMarkAreaData() {
  const bands = [
    { label: "WRC07-1分配", start: 470, end: 500 },
    { label: "WRC07-2分配", start: 500, end: 550 },
    { label: "广电占用", start: 550, end: 600 },
    { label: "广电-2占用", start: 600, end: 650 },
    { label: "非运营商", start: 650, end: 700 },
    { label: "WRC07-3分配", start: 700, end: 770 }
  ]
  const colors = ["#00bcd4", "#2196f3", "#4caf50", "#ff9800", "#9c27b0", "#f44336"]
  return bands.map((band, index) => {
    const startLabel = getAxisLabel(band.start)
    const endLabel = getAxisLabel(band.end)
    return [
      {
        name: band.label,
        xAxis: startLabel,
        itemStyle: { color: colors[index % colors.length] },
        label: {
          show: true,
          position: "insideTop",
          formatter: band.label,
          fontSize: 12,
          fontWeight: "bold",
          color: "#fff"
        }
      },
      { xAxis: endLabel }
    ]
  })
}

// ========== 你原来的信标数据（可选：未来可改为 prop）==========
const beaconData = [
  { channel: 21, value: -104 },
  { channel: 22, value: -98 },
  { channel: 23, value: -88 },
  { channel: 24, value: -88 },
  { channel: 25, value: -104 },
  { channel: 26, value: -103 },
  { channel: 27, value: -83 },
  { channel: 28, value: -77 },
  { channel: 29, value: -60 },
  { channel: 30, value: -60 },
  { channel: 31, value: -76 },
  { channel: 32, value: -91 },
  { channel: 33, value: -104 },
  { channel: 34, value: -104 },
  { channel: 35, value: -104 },
  { channel: 36, value: -104 },
  { channel: 37, value: -104 },
  { channel: 38, value: -92 },
  { channel: 39, value: -104 },
  { channel: 40, value: -104 },
  { channel: 41, value: -102 },
  { channel: 42, value: -82 },
  { channel: 43, value: -60 },
  { channel: 44, value: -80 },
  { channel: 45, value: -73 },
  { channel: 46, value: -88 },
  { channel: 47, value: -104 }
]

// ========== 初始化所有图表 ==========
async function initCharts() {
  await nextTick()

  const commonGrid = { top: 40, bottom: 50, left: 60, right: 20 }

  // --- 频谱图 ---
  if (spectrumRef.value && props.dbValues.length > 0) {
    spectrumChart?.dispose()
    spectrumChart = echarts.init(spectrumRef.value)
    spectrumChart.setOption({
      tooltip: {
        trigger: "axis",
        formatter: (params) => {
          const freq = params[0].name
          const db = params[0].value
          return `频率: ${freq} MHz<br/>强度: ${db.toFixed(2)} dBm`
        }
      },
      xAxis: {
        type: "category",
        data: props.freqLabels,
        name: "频率 (MHz)",
        axisLabel: { color: "#ccc", fontSize: 12 },
        splitLine: { show: false }
      },
      yAxis: {
        type: "value",
        name: "dBm",
        min: -110,
        max: -40,
        axisLabel: { color: "#ccc" }
      },
      series: [{
        type: "line",
        data: props.dbValues,
        smooth: true,
        showSymbol: false,
        lineStyle: { color: "#00ffff", width: 2 },
        areaStyle: { color: "rgba(0, 255, 255, 0.2)" },
        markArea: { data: generateMarkAreaData(), silent: true }
      }],
      grid: commonGrid
    })
  }

  // --- 瀑布图 ---
  if (waterfallRef.value && props.waterfallData.length > 0) {
    waterfallChart?.dispose()
    waterfallChart = echarts.init(waterfallRef.value)
    waterfallChart.setOption({
      tooltip: {
        trigger: "item",
        formatter: (params) => {
          const freq = props.freqLabels[params.data[0]]
          const time = props.waterfallTimes[params.data[1]]
          const db = params.data[2]
          return `频率: ${freq} MHz<br/>时间: ${time}<br/>强度: ${db.toFixed(2)} dBm`
        }
      },
      xAxis: {
        type: "category",
        data: props.freqLabels,
        name: "频率 (MHz)",
        axisLabel: { color: "#ccc", fontSize: 12 },
        splitLine: { show: false }
      },
      yAxis: {
        type: "category",
        data: props.waterfallTimes,
        name: "时间",
        inverse: true,
        axisLabel: { color: "#ccc" }
      },
      visualMap: {
        min: -110,
        max: -40,
        orient: "vertical",
        right: 10,
        top: "middle",
        inRange: { color: ["#000033", "#0000ff", "#00ffff", "#ffff00", "#ff0000"] }
      },
      series: [{
        type: "heatmap",
        data: props.waterfallData,
        label: { show: false },
        markArea: { data: generateMarkAreaData(), silent: true }
      }],
      grid: commonGrid
    })
  }

  // --- 信标柱状图（你原来的逻辑）---
  if (beaconRef.value) {
    beaconChart?.dispose()
    beaconChart = echarts.init(beaconRef.value)
    beaconChart.setOption({
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        formatter: "{b}: {c} dBm"
      },
      xAxis: {
        type: "category",
        data: beaconData.map(d => d.channel),
        axisLabel: { color: "#333", fontSize: 12 },
        axisLine: { lineStyle: { color: "#ccc" } },
        splitLine: { show: false }
      },
      yAxis: {
        type: "value",
        name: "信号强度 (dBm)",
        min: -110,
        max: -40,
        inverse: true,
        axisLabel: { color: "#333", fontSize: 12 },
        splitLine: { lineStyle: { color: "#eee" } },
        axisLine: { lineStyle: { color: "#ccc" } }
      },
      series: [{
        type: "bar",
        data: beaconData.map(d => d.value),
        barWidth: "12px",
        barMinHeight: 1,
        itemStyle: {
          color: function (params) {
            const val = params.value
            if (val >= -60) {
              return "#e74c3c"
            } else if (val >= -80) {
              return "#3498db"
            } else {
              return "#2ecc71"
            }
          }
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
          color: "#333",
          fontSize: 10
        }
      }],
      grid: commonGrid
    })
  }
}

// ========== 响应式更新（当父组件数据变化时）==========
watch(
  () => [props.dbValues, props.waterfallData],
  () => {
    initCharts()
  },
  { deep: true, immediate: true }
)

// ========== 生命周期 ==========
onMounted(() => {
  window.addEventListener("resize", handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize)
  spectrumChart?.dispose()
  waterfallChart?.dispose()
  beaconChart?.dispose()
})

function handleResize() {
  spectrumChart?.resize()
  waterfallChart?.resize()
  beaconChart?.resize()
}
</script>

<style scoped>
.pd-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 0 12px 12px;
}

.chart-wrapper h3,
.signal-chart-container h3 {
  margin: 0 0 12px;
  font-size: 16px;
  color: #fff;
}

.chart {
  width: 100%;
  height: 280px;
  background: #ffffff;
  border-radius: 6px;
}

/* 保留你原来的信标图样式 */
.signal-chart-container {
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.signal-chart-container .chart {
  background: none;
  box-shadow: none;
  border-radius: 0;
}
</style>
